package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.entity.Category;
import com.itheima.entity.Dish;
import com.itheima.entity.Employee;
import com.itheima.mapper.CategoryMapper;
import com.itheima.mapper.DishMapper;
import com.itheima.service.IDishService;
import com.itheima.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements IDishService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public Result saveDish(Dish dish) {
        dish.setStatus(1);
        int r = dishMapper.insert(dish);
        if(r<=0){
            return Result.error("添加失败");
        }
        return Result.success(dish);
    }

    @Override
    public Result deleteById(Long ids) {
        int r = dishMapper.deleteById(ids);
        if(r<=0){
            return Result.error("删除失败");
        }
        return Result.success("删除成功");
    }

    @Override
    public Result status(Integer status, Long ids) {
        //根据id查找菜品
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Dish::getId,ids);
        Dish dish = dishMapper.selectOne(lqw);
        //判断dish是否存在
        if (dish == null){
            return Result.error("菜品不存在");
        }
        //设置菜品的出售状态
        dish.setStatus(status);
        int r = dishMapper.updateById(dish);
        //判断是否修改成功
        if (r<=0){
            return Result.error("修改失败");
        }
        return Result.success(dish);
    }

    @Override
    public Result listDish(Long categoryId) {
        //根据菜系的id，查询菜品
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Dish::getCategoryId,categoryId);
        List<Dish> dishes = dishMapper.selectList(lqw);
        return Result.success(dishes);
    }

    @Override
    public IPage<Dish> getPage(int current, int pageSize, String name) {
        if (name != null){
            LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
            lqw.like(Dish::getName,name);
            IPage<Dish> page = new Page<Dish>(current,pageSize);
            return dishMapper.selectPage(page,lqw);
        }
        IPage<Dish> page = new Page<Dish>(current,pageSize);
        return dishMapper.selectPage(page,null);
    }
}
